﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Sport
{
	public class SportTeam
	{
		public int id;
		public String name;
		public SportTeam(int iid, string iname)
		{
			id = iid;
			name = iname;
		}
	}
	public class SportEvent
	{
		public int round;
		public DateTime eventtime;
		public SportTeam home, away;

		public int score_home;
		public int score_away;
		public SportEvent(int iround, SportTeam ihome, SportTeam iaway, DateTime itime)
		{
			round = iround;
			home = ihome;
			away = iaway;
			eventtime = itime;
		}

		public void SetResult(int home, int away)
		{
			score_home = home;
			score_away = away;
		}
	}

	public class SportTableBase
	{
		public List<SportTeam> teams = new List<SportTeam>();
		public SportTeam GetTeam(int ID)
		{
			for (int i = 0; i < teams.Count; i++)
				if (teams[i].id == ID)
					return teams[i];
			return null;
		}
		public SportTeam CreateTeam(int iid, string iname)
		{
			SportTeam res = new SportTeam(iid, iname);
			teams.Add(res);
			return res;
		}
		public List<SportEvent> events = new List<SportEvent>();

		public List<TableEntry> table = new List<TableEntry>();

		public void BuildTable(int round=-1)
		{
			table.Clear();
			foreach (SportTeam t in teams)
			{
				TableEntry e = CreateEntry(t);
				table.Add(e);
				foreach (SportEvent se in events)
					if (round == -1 || round >= se.round)
						if (se.home == t || se.away == t)
							e.events.Add(se);
				e.CompleteEntry();
			}
			Sort(0, 0, teams.Count);
		}
		public virtual TableEntry CreateEntry(SportTeam iteam)
		{
			return new TableEntry(iteam);
		}
		public virtual void Sort(int stage, int first, int last)
		{
			if (stage == 0)
				table.Sort((x1, x2) => x1.team.id.CompareTo(x2.team.id));
		}
		public void RoundRobin(bool twice)
		{
			for (int i = 0; i < teams.Count; i++)
				for (int j = i + 1; j < teams.Count; j++)
				{
					events.Add(CreateEvent(1,teams[i], teams[j], DateTime.MinValue));
				}
		}
		public SportEvent AddEvent(int round, SportTeam t1, SportTeam t2, DateTime itime)
		{
			SportEvent res = CreateEvent(round, t1, t2, itime);
			events.Add(res);
			return res;
		}
		public SportEvent AddResult(int round,SportTeam t1, SportTeam t2, int s1, int s2)
		{
			SportEvent res = CreateEvent(round, t1, t2, DateTime.MinValue);
			events.Add(res);
			res.SetResult(s1, s2);
			return res;
		}
		protected virtual SportEvent CreateEvent(int round, SportTeam t1, SportTeam t2, DateTime itime)
		{
			return new SportEvent(round, t1, t2, itime);
		}
	}
	public class TableEntry
	{
		public SportTeam team;
		public int points = 0;
		public List<SportEvent> events = new List<SportEvent>();
		public TableEntry(SportTeam iteam)
		{
			team = iteam;
		}

		public virtual void CompleteEntry()
		{
		}
	}
}